import * as qiniu from 'qiniu-js';

/** qiniu-js@v3 */
class QiniuKodo {
  // status = 0;//0.prepare 1.processing 2.done 3.error

  constructor(token, config) {
    this.authToken = token;
    this.config = config;
    this.status = 0;
  }

  run(file, key, saveKey, callback = {}) {
    if (this.status === 1) return;

    // 设置状态为处理中状态
    this.status = 1;

    // 统一回调处理
    const {
      updateProgress,
      onSuccess,
      onError
    } = callback;
    const observable = qiniu.upload(file, saveKey, this.authToken, this.config);
    const observer = {
      complete: (response) => {
        this.status = 2;

        if (onSuccess) {
          onSuccess({
            key,
            response: {
              fileName: file.name,
              ...response
            }
          });
        }
      },
      error: (info) => {
        this.status = 3;

        // error code => https://developer.qiniu.com/kodo/3928/error-responses
        if (onError) {
          onError({
            key,
            error: info
          });
        }
      },
      next: (data) => {
        if (updateProgress) {
          updateProgress({
            key,
            percent: data.total.percent
          });
        }
      }
    };

    this.subscription = observable.subscribe(observer);
  }
  
  abort() {
    if (this.subscription) {
      this.subscription.unsubscribe();
      this.status = 0;
    }
  }
}

export default QiniuKodo;